'use strict';

var allCitys = require('../city.json');

var areaSuffixes = ['省', '市', '县', '区'];
exports.query = function (parent) {
    var cityList = allCitys;

    if (parent) {
        var found = cityList.some(function find(item) {
            if (item.name === parent) {
                cityList = item.children;
                return true;
            } else if (item.children && item.children.length) {
                return item.children.some(find);
            } else {
                return false;
            }
        });

        if (!found) {
            return [];
        }
    }

    return cityList.map(function (city) {
        return city.name;
    });
};

exports.queryFuzzy = function (parent) {
    var cityList = allCitys;
    let parentRegex = new RegExp(parent, 'i');
    if (parent) {
        var found = cityList.some(function find(item) {
            if (parentRegex.test(nameNoSuffix(item.name))) {
                cityList = item.children;
                return true;
            } else if (item.children && item.children.length) {
                return item.children.some(find);
            } else {
                return false;
            }
        });

        if (!found) {
            return [];
        }
    }

    return cityList.map(function (city) {
        return nameNoSuffix(city.name);
    });
};

function nameNoSuffix(name) {
    if (!name) {
        return false;
    }
    var suffix;

    for (var i = 0; i < areaSuffixes.length; i++) {
        if (endWith(name, areaSuffixes[i])) {
            suffix = areaSuffixes[i];
            break;
        }
    }
    if (suffix) {
        return name.substr(0, name.length - suffix.length);
    }
    return name;
}
function endWith(str, suffix) {

    if (typeof suffix === 'undefined' || suffix === null) {
        return false;
    }

    str = String(str);
    suffix = String(suffix);

    var i = suffix.length;
    var l = str.length - i;

    while (i--) {
        if (suffix.charAt(i) !== str.charAt(l + i)) {
            return false;
        }
    }
    return true;
};

exports.provinces = allCitys;
